<template>
  <div class="divBox">
    <el-card class="box-card">

      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <p style="margin-left: 120px;margin-bottom: 20px"><strong>房屋地址</strong></p>
          <el-form v-loading="saveLoading" size="small" ref="form" :model="form" :rules="rules" label-width="190px" @submit.native.prevent>

            <el-form-item label="房屋类型：" prop="houseType">
              <el-button-group >
                <el-button style="width: 120px"
                    v-for="type in houseTypeOptions"
                    :key="type.id"
                    :type="form.houseType === type.houseTypeName ? 'primary' : ''"
                    plain
                    @click="selectHouseType(type.houseTypeName)"
                >
                  {{ type.houseTypeName }}
                </el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item label="租赁证编号：" prop="leaseCertificateNumberNew">
              <el-input v-model="form.leaseCertificateNumberNew" placeholder="租赁证编号" style="width: 40%" :disabled="isDisabled">
              </el-input>
              <el-button @click="certificateNumber" style="margin-left: 20px" :disabled="isDisabled">生成租赁证编号</el-button>
            </el-form-item>

            <el-form-item label="片区与街道：" prop="areaStreet">
              <el-cascader
                  style="width: 40%"
                  :disabled="isDisabled"
                  v-model="areaStreet"
                  :options="options"
                  :props="{
                        value: 'name',
                        label: 'name',
                        children: 'children',
                      }"
                  filterable
              ></el-cascader>
              <el-button @click="addTem" style="margin-left: 20px" :disabled="isDisabled">片区与街道管理</el-button>
            </el-form-item>
            <el-form-item label="详细地址：">
              <el-input v-model="form.buildingNumber" placeholder="请输入楼号" style="width: 8.2%" :disabled="isDisabled"></el-input>
              <span class="separator">-</span>
              <el-input v-model="form.unitNumber" placeholder="请输入单元" style="width: 8.2%" :disabled="isDisabled"></el-input>
              <span class="separator">-</span>
              <el-input v-model="form.floorLevel" placeholder="请输入楼层" style="width: 8.2%" :disabled="isDisabled" @change="calculateHousingRent"></el-input>
              <span class="separator">-</span>
              <el-input v-model="form.roomNumber" placeholder="请输入户号" style="width: 8.2%" :disabled="isDisabled"></el-input>
            </el-form-item>
            <el-form-item label="房屋方位：" prop="houseDirection">
              <el-input v-model="form.houseDirection" placeholder="请输入房屋方位" style="width: 40%" :disabled="isDisabled"></el-input>
            </el-form-item>
            <el-form-item label="结构：" prop="structureType">
              <el-select v-model="form.structureType" placeholder="请选择房屋类型" style="width: 40%" :disabled="isDisabled">
                <el-option
                    v-for="item in structureTypeOptions"
                    :key="item.id"
                    :label="item.content"
                    :value="item.content">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="房屋状态：" prop="houseStatus">
              <el-select v-model="form.houseStatus" placeholder="请选择房屋状态" style="width: 40%" :disabled="isDisabled">
                <el-option
                    v-for="item in houseStatusOptions"
                    :key="item.id"
                    :label="item.content"
                    :value="item.content">
                </el-option>
              </el-select>
            </el-form-item>

            <p style="margin: 40px 0 20px 120px"><strong>明细记载</strong></p>
            <el-form-item label="房屋类区：" prop="houseAreaType">
              <el-select v-model="form.houseAreaType" placeholder="请选择房屋类区" style="width: 40%" :disabled="isDisabled" @change="calculateHousingRent">
                <el-option
                    v-for="item in fwlqOptions"
                    :key="item.id"
                    :label="item.lqValue"
                    :value="item.lqValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="建筑面积/使用面积：" >
              <el-input v-model="form.buildingArea" placeholder="建筑面积" style="width: 18.8%" :disabled="isDisabled">
              </el-input>
              <span class="separator">/</span>
              <el-input v-model="form.usableArea" placeholder="使用面积" style="width: 18.8%" :disabled="isDisabled" @change="calculateHousingRent">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="阳台建筑面积/使用面积：">
                  <el-input v-model="form.balconyBuildingArea" placeholder="建筑面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                  <span style="margin: 0 2.5%;color: gray" >/</span>
                  <el-input v-model="form.balconyUsableArea" placeholder="使用面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="阴台建筑面积/使用面积：">
                  <el-input v-model="form.shadyBalconyBuildingArea" placeholder="建筑面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                  <span style="margin: 0 2.5%;color: gray">/</span>
                  <el-input v-model="form.shadyBalconyUsableArea" placeholder="使用面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="地下室建筑面积/使用面积：" >
                  <el-input v-model="form.basementBuildingArea" placeholder="建筑面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                  <span style="margin: 0 2.5%;color: gray">/</span>
                  <el-input v-model="form.basementUsableArea" placeholder="使用面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="其他建筑面积/使用面积：">
                  <el-input v-model="form.otherBuildingArea" placeholder="建筑面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                  <span style="margin: 0 2.5%;color: gray">/</span>
                  <el-input v-model="form.otherUsableArea" placeholder="使用面积" style="width: 42.5%" :disabled="isDisabled">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>




            <p style="margin: 40px 0 20px 120px"><strong>自动计算</strong></p>
            <el-form-item label="应交标准：" prop="yingjiaobiaozhun">
              {{yingjiaobiaozhun}}
            </el-form-item>
            <el-form-item label="调节因素：" prop="policyReduction">
              {{form.policyReduction}}
            </el-form-item>
            <el-form-item label="实收标准：" prop="shishoubiaozhun">
              {{shishoubiaozhun}}
            </el-form-item>
            <el-form-item label="合计月租：" prop="totalMonthlyRent">
              {{form.totalMonthlyRent}}
            </el-form-item>

            <el-form-item>
              <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                         @click="handlerSubmit" v-has-permi="['admin:house:information:save']">保存
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="承租人信息" name="second">
          <lessee :id="form.id" :uniqueId="form.idValue" :leaseCertificateNumber="form.leaseCertificateNumberNew" :isDisabled="isDisabled"></lessee>
        </el-tab-pane>
        <el-tab-pane label="租赁情况" name="third">
          <LeaseSituation :id="form.id" :uniqueId="form.idValue" :isDisabled="isDisabled"></LeaseSituation>
        </el-tab-pane>
      </el-tabs>


    </el-card>

    <!-- 弹窗 -->
    <CreatTemplates ref="addTemplates" />


  </div>
</template>
<script>
import CreatTemplates from "@/views/house/information/components/creteTemplates.vue";
import Lessee from "@/views/house/information/components/lessee.vue";
import LeaseSituation from "@/views/house/information/components/leaseSituation.vue";
import {
  detail,
  generateLeaseCertificateNumberNewApi,
  getAdminGetFwlx, getAreaStreetListDropDown, getFwlqList,
  getFwState, getHousingRentApi,
  save
} from "@/api/house";

export default {
  components: {Lessee, CreatTemplates,LeaseSituation},
  data() {
    return {
      isDisabled: this.$route.params.isDisabled==='1'?true:false,
      areaStreet:[],
      form: {
        id: null,
        idValue: null,
        houseType:'',
        leaseCertificateNumber:'',
        leaseCertificateNumberNew:'',
        areaName:'',
        streetName:'',
        buildingNumber: '',
        unitNumber: '',
        roomNumber: '',
        buildingArea:'',
        usableArea:'',
        houseStatus:'',
        floorLevel:'',
        houseDirection:'',
        unitPricePerSquare:'',
        pqxs:'',
        lcxs:'',
        hjxs:'',
        structureType:'',
        balconyBuildingArea:'',
        balconyUsableArea:'',
        shadyBalconyBuildingArea:'',
        shadyBalconyUsableArea:'',
        otherBuildingArea:'',
        otherUsableArea:'',
        totalPrice:'',
        currentTenantName:'',
        fwlqList:'',
        houseAreaType:'',
        basementBuildingArea:'',
        basementUsableArea:'',
        policyReduction:'',
        totalMonthlyRent:'',
      },
      uniqueId:'',
      shishoubiaozhun:'',
      yingjiaobiaozhun:'',
      activeName: 'first',
      rules: {
        houseType: [{required: true, message: '请选择房屋类型', trigger: ['blur']}],
        leaseCertificateNumberNew: [{required: true, message: '请填写租赁证编号', trigger: ['blur']}],
        streetName: [{required: true, message: '请选择片区/街', trigger: ['blur']}],
        buildingNumber: [{required: true, message: '请输入楼号', trigger: ['blur']}],
        unitNumber: [{required: true, message: '请输入单元', trigger: ['blur']}],
        floorLevel: [{required: true, message: '请输入楼层', trigger: ['blur']}],
        roomNumber: [{required: true, message: '请选择房号', trigger: ['blur']}],
        houseAreaType: [{required: true, message: '请选择房屋类区', trigger: ['blur']}],
      },
      saveLoading: false,
      certificateNumberLoading: false,
      formLoading: false,
      options: [],
      houseTypeOptions: [],
      structureTypeOptions: [],
      houseStatusOptions: [],
      fwlqOptions: [],
      housingRent: {},
      dialogVisible: false, // 控制弹窗显示/隐藏
    }
  },
  mounted() {
    if (this.$route.params.id) {
      this.getDetail();
    }
    this.getHouseType();
    this.getStreetName();
    this.getHouseStatus();
    this.getStructureType();
    this.getFwlq();

  },
  methods: {
    getDetail() {
      this.tableLoading = true
      detail(this.$route.params.id).then(res => {
        this.form = res;
        this.shishoubiaozhun = res.shishoubiaozhun;
        this.yingjiaobiaozhun = res.yingjiaobiaozhun;
        this.form.policyReduction = res.tiaojieyinsu;
        this.form.totalMonthlyRent = res.hejiyuezu;
        this.areaStreet = [res.areaName, res.streetName]
      }).finally(() => {
        this.tableLoading = false;
        // this.calculateHousingRent();
      })

      this.form = this.editData
    },
    handlerSubmit() {
      if (this.saveLoading) {
        return
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        this.form.areaName = this.areaStreet[0];
        this.form.streetName = this.areaStreet[1];

        if(this.form.leaseCertificateNumber===''){
          this.form.leaseCertificateNumber = this.form.leaseCertificateNumberNew
        }

        save(this.form).then((res) => {
          this.$message.success('保存成功');
          this.form.id = res.id;
          this.form.idValue = res.idValue
          this.saveLoading = false;
          // this.activeName = 'second';
          this.$nextTick(() => {
            // 调用承租人组件的加载方法
            if (this.$refs.lessee) {
              this.$refs.lessee.getPositionList();
            }
          });
        })
      })
    },
    addTem() {
      this.$refs.addTemplates.dialogVisible = true
    },
    getHouseType() {
      // 获取房屋类型
      getAdminGetFwlx().then((res) => {
        this.houseTypeOptions = res
      })
    },
    // 获取片区与街道
    getStreetName() {
      getAreaStreetListDropDown().then((res) => {
        this.options = res
      })
    },
    // 获取房屋状态
    getHouseStatus() {
      getFwState({dicType:'fwzt'}).then((res) => {
        this.houseStatusOptions = res
      })
    },
    // 获取房屋结构
    getStructureType() {
      getFwState({dicType:'fwjg'}).then((res) => {
        this.structureTypeOptions = res
      })
    },
    // 获取房屋类区
    getFwlq() {
      getFwlqList().then((res) => {
        this.fwlqOptions = res
      })
    },
    // 计算房屋租金
    calculateHousingRent() {
      if(this.form.floorLevel !=='' && this.form.floorLevel !==null
          && this.form.houseType !=='' && this.form.houseType !==null
          && this.form.houseAreaType !=='' && this.form.houseAreaType !==null
          && this.form.usableArea !=='' && this.form.usableArea !==null){
        getHousingRentApi({floorLevel :this.form.floorLevel, houseType:this.form.houseType,houseAreaType:this.form.houseAreaType,usableArea:this.form.usableArea}).then((res) => {
          this.shishoubiaozhun= res.shishoubiaozhun
          this.form.policyReduction= res.tiaojieyinsu
          this.yingjiaobiaozhun= res.yingjiaobiaozhun
          this.form.totalMonthlyRent= res.hejiyuezu
        })
      }

    },
    certificateNumber() {
      // 先校验房屋类型是否已选择
      if (!this.form.houseType) {
        this.$message.warning('请先选择房屋类型！');
        return; // 直接退出，不执行后续逻辑
      }

      this.certificateNumberLoading = true;
      generateLeaseCertificateNumberNewApi(this.form.houseType)
          .then((res) => {
            if (!res.leaseCertificateNumberNew || !res.leaseCertificateNumber) {
              this.$message.success('请手动输入租赁证编号！');
            } else {
              this.$message.success('已成功生成！');
              this.form.leaseCertificateNumberNew = res.leaseCertificateNumberNew;
              this.form.leaseCertificateNumber = res.leaseCertificateNumber;
            }
          })
          .finally(() => {
            this.certificateNumberLoading = false;
          });
    },
    selectHouseType(type) {
      this.form.houseType = type;
    }


  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


/* 自定义弹窗样式 */
.right-dialog {
  position: fixed;
  top: 0;
  left:60%; /* 定位到页面最右侧 */
  bottom: 0;
  margin: 0 !important; /* 清除默认 margin */
  height: 100vh !important; /* 高度占满整个视口 */
  width: 40% !important; /* 宽度为 30% */
  transform: none !important; /* 清除默认 transform */
  .el-dialog__header {
    text-align: left;
    padding: 20px; /* 根据需要调整 */
  }

  .el-dialog__body {
    height: calc(100% - 130px); /* 假设头部和底部总高度是100px, 可以根据实际情况调整 */
    overflow-y: auto; /* 如果内容超出，启用垂直滚动 */
  }

  .el-dialog__footer {
    padding: 10px; /* 根据需要调整 */
    text-align: right;
  }
}
.separator {
  margin: 0 1.05%; /* 左右各 8px，总计 16px */
  color: gray; /* 灰色 */
}

</style>
